package Exc.controller;

import Exc.domain.JSONResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;

/**
 * The type Ssm exception handler.
 */
//  对控制器进行增强(动态代理)
@ControllerAdvice
public class SSMExceptionHandler {
    /**
     * Handle exception.
     *
     * @param ex       the ex
     * @param method   the method
     * @param response the response
     */
//这个方法是在控制器出异常之后， springmvc 自动调用
    //补捕获运行过程中出现的异常
    @ExceptionHandler(Exception.class)
    public void handleException(Exception ex, HandlerMethod method, HttpServletResponse response) {
        String page = null;
        try {
            ex.printStackTrace();
            System.out.println(method.getMethod().getName());
            //如果是ajax
            JSONResult jsonResult = new JSONResult(false,"出现异常，操作失败");
            response.setContentType("application/json;charset=utf-8");
            ObjectMapper mapper = new ObjectMapper();
            String jsonStr = mapper.writeValueAsString(jsonResult);
            response.getWriter().print(jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
